// 支付与会员功能
function initPaymentModule() {
  // 钱包充值功能
  initWalletRecharge();
  
  // VIP会员开通功能
  initVipActivation();
  
  // 订单查询功能
  initOrderQuery();
}

// 钱包充值功能
function initWalletRecharge() {
  const rechargeForm = document.getElementById('rechargeForm');
  if (!rechargeForm) return;
  
  rechargeForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    // 检查登录状态
    if (checkNeedLogin()) return;
    
    const amount = document.getElementById('rechargeAmount').value;
    
    // 创建充值订单
    paymentAPI.createOrder(userToken, 'recharge', null, amount)
      .then(response => {
        if (response.code === 200) {
          // 支付订单
          return paymentAPI.payOrder(userToken, response.data.orderNo, 'alipay');
        } else {
          throw new Error(response.message || '创建充值订单失败');
        }
      })
      .then(response => {
        if (response.code === 200) {
          showToast('充值成功');
          
          // 更新用户信息
          return authAPI.getUserInfo(userToken);
        } else {
          throw new Error(response.message || '支付失败');
        }
      })
      .then(response => {
        if (response.code === 200) {
          currentUser = response.data;
          updateUIForLoggedInUser();
          
          // 更新钱包余额显示
          const balanceElement = document.getElementById('walletBalance');
          if (balanceElement) {
            balanceElement.textContent = currentUser.balance.toFixed(2);
          }
        }
      })
      .catch(error => {
        showToast(error.message || '充值失败');
      });
  });
}

// VIP会员开通功能
function initVipActivation() {
  const activateVipBtn = document.getElementById('activateVipBtn');
  if (!activateVipBtn) return;
  
  activateVipBtn.addEventListener('click', function() {
    // 检查登录状态
    if (checkNeedLogin()) return;
    
    // 检查是否已是VIP
    if (currentUser && currentUser.isVip) {
      showToast('您已经是VIP会员');
      return;
    }
    
    // 创建VIP订单
    paymentAPI.createOrder(userToken, 'vip', null, 9.9)
      .then(response => {
        if (response.code === 200) {
          // 支付订单
          return paymentAPI.payOrder(userToken, response.data.orderNo, 'alipay');
        } else {
          throw new Error(response.message || '创建VIP订单失败');
        }
      })
      .then(response => {
        if (response.code === 200) {
          // 激活VIP
          return paymentAPI.activateVip(userToken);
        } else {
          throw new Error(response.message || '支付失败');
        }
      })
      .then(response => {
        if (response.code === 200) {
          showToast('VIP开通成功');
          
          // 更新用户信息
          return authAPI.getUserInfo(userToken);
        } else {
          throw new Error(response.message || 'VIP激活失败');
        }
      })
      .then(response => {
        if (response.code === 200) {
          currentUser = response.data;
          updateUIForLoggedInUser();
          
          // 更新VIP状态显示
          const vipStatusElement = document.getElementById('vipStatus');
          const vipExpireElement = document.getElementById('vipExpireTime');
          
          if (vipStatusElement) {
            vipStatusElement.textContent = currentUser.isVip ? 'VIP会员' : '普通用户';
          }
          
          if (vipExpireElement && currentUser.vipExpireTime) {
            vipExpireElement.textContent = currentUser.vipExpireTime;
          }
        }
      })
      .catch(error => {
        showToast(error.message || 'VIP开通失败');
      });
  });
}

// 订单查询功能
function initOrderQuery() {
  const orderQueryBtn = document.getElementById('orderQueryBtn');
  if (!orderQueryBtn) return;
  
  orderQueryBtn.addEventListener('click', function() {
    // 检查登录状态
    if (checkNeedLogin()) return;
    
    // 获取订单列表
    paymentAPI.getOrderList(userToken)
      .then(response => {
        if (response.code === 200) {
          showOrderList(response.data);
        } else {
          throw new Error(response.message || '获取订单列表失败');
        }
      })
      .catch(error => {
        showToast(error.message || '获取订单列表失败');
      });
  });
}

// 显示订单列表
function showOrderList(data) {
  const orderListContainer = document.getElementById('orderListContainer');
  if (!orderListContainer) return;
  
  orderListContainer.style.display = 'block';
  
  const orderListContent = document.getElementById('orderListContent');
  if (orderListContent) {
    if (data.orders && data.orders.length > 0) {
      let html = `
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单编号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">产品类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
      `;
      
      data.orders.forEach(order => {
        const productTypeMap = {
          'bazi_detail': '八字详解',
          'character_detail': '性格详解',
          'fengshui_detail': '风水详解',
          'vip': 'VIP会员',
          'recharge': '钱包充值'
        };
        
        const statusMap = {
          0: '未支付',
          1: '已支付',
          2: '已取消'
        };
        
        html += `
          <tr>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.orderNo}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${productTypeMap[order.productType] || order.productType}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">¥${order.amount.toFixed(2)}</td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${order.status === 1 ? 'bg-green-100 text-green-800' : order.status === 0 ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'}">
                ${statusMap[order.status] || '未知'}
              </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${order.createTime}</td>
          </tr>
        `;
      });
      
      html += `
          </tbody>
        </table>
      `;
      
      orderListContent.innerHTML = html;
    } else {
      orderListContent.innerHTML = `
        <div class="text-center py-8 text-gray-500">
          暂无订单记录
        </div>
      `;
    }
  }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  initPaymentModule();
});
